package iedcyt.acute.model;

import iedcyt.acute.businessServices.ViewLogger;
import iedcyt.acute.dataAccess.utils.BeansXML;
import iedcyt.acute.dataAccess.utils.Pair;

import java.util.HashMap;

public class BeansConfigurationModel {
	
	private boolean changed;
	private HashMap<String, String> dbBeans;
	private Pair<String, String> selectedKey;

	public BeansConfigurationModel() {
		selectedKey = null;
		dbBeans = new HashMap<String,String>();
		dbBeans.put("MAAUCODataSource", BeansXML.getInstance().getDatabasePath("MAAUCODataSource"));
		dbBeans.put("ACUTE1dataSource", BeansXML.getInstance().getDatabasePath("ACUTE1dataSource"));
		dbBeans.put("auxDataSource", BeansXML.getInstance().getDatabasePath("auxDataSource"));
		dbBeans.put("maesorgDataSource", BeansXML.getInstance().getDatabasePath("maesorgDataSource"));
		
		changed = false;
	}
	
	public void setDbBeans(HashMap<String, String> dbBeans) {
		this.dbBeans = dbBeans;
	}
	public HashMap<String, String> getDbBeans() {
		return dbBeans;
	}
	public void setChanged(boolean changed) {
		this.changed = changed;
	}
	public boolean isChanged() {
		return changed;
	}
	public void changeKeyData(String key, String value) {
		selectedKey = new Pair<String, String>(key, value);
		dbBeans.put(key, value);
		changed = true;
	}

	public void save() {
		for (String key : dbBeans.keySet()) {
			BeansXML.getInstance().setDatabasePath(key, dbBeans.get(key));
		}
		
		if (BeansXML.getInstance().saveChanges())
			ViewLogger.getInstance().info("Cambios guardados correctamente");
		else ViewLogger.getInstance().error("No se han podido guardar los cambios");
	}
	
	public void changeKeyDataByDialog(String path) {
		if (selectedKey != null) {
			String key = selectedKey.getFirst();
			String value = selectedKey.getSecond();
			
			if (value.contains("jdbc:sqlite:")) 
				value = "jdbc:sqlite:" + path.replace("\\", "\\\\");
			else if (value.contains("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="))
				value = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + path.replace("\\", "\\\\");
			
			dbBeans.put(key, value);
			changed = true;
		}
	}
	
	public Pair<String, String> getSelectedKey() {
		return selectedKey;
	}

	public void setSelectedKey(String key, String value) {
		this.selectedKey = new Pair<String,String>(key,value);
		 
	}
	
	
	

}
